import Taro, {Component, Config} from '@tarojs/taro'
import { Button, View, Text } from '@tarojs/components'
import './index.scss'
import {formatTime, isWeChat} from "@/utils/utils"
import {getBrand, getSharePath, goodsScore} from '@/utils/storage'
import UnpaidCountdown from '@/components/countdown/unpaid/index'
import {Loading, WalletPay, OrderGoodsList, FyImg} from "@/components/index"
import {getOrderInfo, goToWechatPay, cancelOrderInfo, goToWalletPay, goH5ToPay, goToPayInMp} from "@/api/orderApi"
import {PAY_TYPE, ORDER_TYPE, ADDITIONAL} from "@/config/types"
import OrderCardGoodsTwo from "@/components/order/cart-goods-two";
import {toOrderListPage, toOrderUnpaidPage} from "@/utils/page_router";
import {SERVICE_URL_V1} from "@/config/config";
import {getJsSdk} from "@/api/oauthApi";
import styles from "../calc/index.module.scss";
import DeliveryIcon from "@/assets/images/delivery-icon.png";
import DiscountsIcon from "@/assets/images/discounts-icon.png";
// import { toGoodsPage } from "@/utils/page_router"

export default class Index extends Component {
  state: any
  config: Config = {
    navigationBarTitleText: '订单详情',
    navigationBarTextStyle: process.env.navigationBarTextStyle,
    navigationBarBackgroundColor: process.env.backgroundColor
  }
  static options = {
    addGlobalClass: true
  }

  constructor() {
    super(...arguments)
    const { params } = this.$router
    this.state = {
      id: params.id,
      seconds: undefined,
      loading: true,
      cartList: [],
      userInfo: {},
      orderInfo: {},
      showWallet: false,
      tipList: ADDITIONAL
    }
  }

  componentDidShow() {
    isWeChat() && this.getWxConfig()
    this.getOrderInfo()

  }

  //  分享小程序
  onShareAppMessage() {
    const { cartList } = this.state
    const names = cartList.map(goods => goods.name)
    return { title: `${names.join('、')}`, path: getSharePath() }
  }

  /**
   * 获取订单信息
   * @param id 订单id
   */
  getOrderInfo() {
    const { id } = this.state
    getOrderInfo(id).then(res => {
      const { data } = res
      this.setState({
        seconds: data.unPaidSeconds,
        cartList: data.cartSnap,
        userInfo: data.addressSnap,
        orderInfo: data,
        storeInfo: data.cooperateShopAddressSnap,
        loadingStatus: false
      }, () => {
        this.setState({
          loading: false
        })
      })
    })
  }

  /**
   * 倒计时时间到
   */
  onTimeUp() {
    console.log('onTimeUp')
    // const { orderInfo } = this.state
    // wx.showLoading({title: '加载中', mask: true})
    // cancelOrderInfo(orderInfo.id).then(() => {
    //   wx.hideLoading()
    //   wx.showToast({ title: '订单已取消', icon: 'success' })
    //   wx.navigateBack()
    // })
    // wx.showToast({title: '时间到', icon: 'none'})
  }

  //  取消订单
  onCloseOrder(id) {
    Taro.showLoading({title: '加载中', mask: true})
    cancelOrderInfo(id).then(() => {
      Taro.hideLoading()
      Taro.showToast({ title: '订单已取消', icon: 'success' })
      toOrderListPage(true)
    })
  }

  //  立即支付
  onPayOrder(info) {
    Taro.showLoading({title: '加载中', mask: true})
    goH5ToPay(info.id).then(({ data }) => {
      Taro.hideLoading()
      window.location.replace(data)
    })
    // if (info.payType === PAY_TYPE.WECHAT) {
    //   wx.showLoading({title: '加载中', mask: true})
    //   goToWechatPay(info.id).then(res => {
    //     Taro.requestPayment(res.data).then(() => {
    //       wx.hideLoading()
    //       wx.showToast({ title: '支付成功', icon: 'success' })
    //       this.getOrderInfo()
    //     }).catch(() => {
    //       wx.hideLoading()
    //       wx.showToast({ title: '支付取消', icon: 'none' })
    //     })
    //   })
    // } else {
    //   this.setState({
    //     showWallet: true
    //   })
    // }
  }

  //  公众号微信支付
  // async wechatPay(orderInfo) {
  //   Taro.showLoading({ title: '请稍后', mask: true })
  //   goToPayInMp(orderInfo.id).then(res => {
  //     let data = res.data
  //     Taro.hideLoading()
  //     Taro.requestPayment({
  //       ...data,
  //       success: () => {
  //
  //       },
  //       fail: function () {
  //
  //       }
  //     })
  //   })
  // }

  //  显示选择弹出窗口
  showSelectPopup(name, bool) {
    this.setState({
      [name]: bool
    })
  }

  //  获取微信配置
  getWxConfig() {
    getJsSdk(['chooseWXPay']).then(({ data }) => {
      wx.config(data)
    })
  }

  //  确定钱包支付
  onConfirmWalletPay() {
    const { orderInfo }:any = this.state
    wx.showLoading({ title: '请稍后', mask: true })
    goToWalletPay(orderInfo.id).then(() => {
      wx.hideLoading()
      wx.showToast({ title: '扣款成功', icon: 'success' })
      this.showSelectPopup('showWallet', false)
      this.getOrderInfo()
    })
  }

  getPay() {
    const openId = Taro.getStorageSync('OPEN_ID')
    console.log(openId)
    const { orderInfo: { payType }, id } = this.state
    if (isWeChat()) {
      this.wechatPay(id)
    } else {
      if (payType === PAY_TYPE.WECHAT) {
        this.h5WechatPay(id)
      } else {
        this.h5AliPay(id)
      }
    }
  }


  //  H5 微信支付
  h5WechatPay(orderId) {
    goH5ToPay(orderId).then(({ data }) => {
      Taro.hideLoading()
      window.location.replace(data)
    })
  }

  //  H5 支付宝支付
  h5AliPay(orderId) {
    Taro.hideLoading()
    window.location.replace(`${SERVICE_URL_V1}/ali-pays/h5-to-pay/${orderId}`)
  }

  //  公众号微信支付
  wechatPay(orderId) {
    // Taro.showToast({title: '这是刚进来'})
    goToPayInMp(orderId).then(res => {
      let data = res.data
      Taro.hideLoading()
      Taro.requestPayment({
        ...data,
        success: () => {
          // // Taro.showToast({title: '这是成功'})
          // Taro.hideLoading()
          Taro.showToast({ title: '支付成功', icon: 'success', complete: function () {
              toOrderListPage(true)
            }
          })
        },
        fail: function () {
          // Taro.showToast({title: '这是失败'})
          Taro.showToast({ title: '支付取消', icon: 'none', complete: function () {
              toOrderUnpaidPage(orderId, true)
            }
          })
        }
      })
    })
  }

  render() {
    const { loading, cartList, userInfo, orderInfo, storeInfo, seconds, showWallet, tipList } = this.state
    return (<View className='detail-page unpaid-page'>
      {loading && <Loading isCover/>}
      <View className='order-card detail-header d-f f-d-c p-0'>
        <View className='count-down d-f f-d-c a-i-c j-c-c'>
          <View className='count-text'>支付剩余时间</View>
          <UnpaidCountdown seconds={seconds} className='count-num bnn-number' onTimeUp={this.onTimeUp.bind(this)}/>
          {/*<View>联系客服</View>*/}
          {/*<OrderCountdown seconds={seconds} className='count-num bnn-number' onTimeUp={this.onTimeUp.bind(this)}/>*/}
        </View>
        {orderInfo.distribute === 1 && <View className='order-card__body user-info d-f f-d-c f-w-w'>
          <View className='user-box d-f a-i-c j-c-b'>
            <View className='user-name t-o-e'>{storeInfo.shopName}</View>
            <View className='user-phone t-o-e'>{storeInfo.phone}</View>
          </View>
          <View className='user-box user-address'>{storeInfo.address}</View>
        </View>}
        {orderInfo.distribute === 0 && <View className='order-card__body user-info d-f f-d-c f-w-w'>
          <View className='user-box d-f a-i-c j-c-b'>
            <View className='user-name t-o-e'>{userInfo.name}</View>
            <View className='user-phone t-o-e'>{userInfo.telephone}</View>
          </View>
          <View className='user-box user-address'>{userInfo.city} {userInfo.detail}</View>
        </View>}
      </View>

      <View className='order-card order-card__body'>
        <View className='cart-list'>
          {cartList.map(cart => {
            return (<OrderCardGoodsTwo key={cart.id} info={cart} isJump className='cart-item thin-border__b'/>)
          })}
          <View className={styles.tips}>
            <View className={styles.tipLeft}>放心购</View>
            <View className={styles.tipList}>
              {tipList.map(item => {
                return (<View className={styles.tipsItem}>{item}</View>)
              })}
            </View>
          </View>
        </View>

        <View>
          <View className={styles.delivery}>
            <View className='d-f a-i-c'>
              <FyImg src={DeliveryIcon} className={styles.Icon}/>
              <View>配送方式</View>
            </View>
            <View>免费包邮</View>
          </View>
          {<View className={styles.discounts}>
            <View className='d-f a-i-c'>
              <FyImg src={DiscountsIcon} className={styles.Icon} />
              <View>平台优惠</View>
            </View>
            <View className={styles.productPrice}>
              <View className={styles.priceItem}>
                <View>商品总价</View>
                <View>
                  {goodsScore(orderInfo.deductScore) && <Text>{orderInfo.deductScore}{getBrand()}+</Text>}
                  {orderInfo.payAmount}元</View>
              </View>
              <View className={styles.priceItem}>
                {/*<View>{getBrand()}已抵扣</View>*/}
                <View>优惠金额</View>
                <View>{Number(orderInfo.originAmount) - Number(orderInfo.payAmount)}元</View>
              </View>
            </View>
          </View>}
        </View>
        {/*<OrderGoodsList list={cartList}/>*/}
        {/*<View className='cart-list'>*/}
        {/*  {cartList.map((item) => {*/}
        {/*    return (<View key={item.id} className='goods-info d-f thin-border__b' onClick={() => toGoodsPage(item)}>*/}
        {/*      <Image src={headImg(item.images)} className='goods-img'/>*/}
        {/*      <View className='goods-right d-f f-d-c j-c-b'>*/}
        {/*        <View className='goods-name t-o-e'>{item.name}</View>*/}
        {/*        <View className='goods-sku t-o-e-2'>{item.specSnap}</View>*/}
        {/*        <View className='d-f j-c-b'>*/}
        {/*          <View className='goods-price bnn-number'>￥{formatAmount(item.amount)}</View>*/}
        {/*          <View className='goods-num'>x{item.number}</View>*/}
        {/*        </View>*/}
        {/*      </View>*/}
        {/*    </View>)*/}
        {/*  })}*/}
        {/*</View>*/}
        {/*<View className='detail-list'>*/}
          {/*<View className='detail-item'>*/}
          {/*  <View className='item-left'>优惠金额：</View>*/}
          {/*  <View className='item-right bnn-number'>￥{orderInfo.discountAmount}</View>*/}
          {/*</View>*/}
          {/*<View className='detail-item'>*/}
          {/*  <View className='item-left'>共{cartList.length}件商品</View>*/}
          {/*  <View className='item-right pay-amount bnn-number'>￥{orderInfo.payAmount}</View>*/}
          {/*</View>*/}
        {/*</View>*/}
      </View>

      <View className='order-card'>
        <View className='order-card__head'>订单信息</View>
        <View className='order-card__body'>
          <View className='detail-list'>
            <View className='detail-item'>
              <View className='item-left'>订单编号：</View>
              <View className='item-right'>{orderInfo.id}</View>
            </View>
            <View className='detail-item'>
              <View className='item-left'>订单时间：</View>
              <View className='item-right'>{formatTime(orderInfo.createdAt)}</View>
            </View>
            <View className='detail-item'>
              <View className='item-left'>订单备注：</View>
              <View className='item-right'>{orderInfo.remark || '无'}</View>
            </View>
          </View>
        </View>
      </View>

      {ORDER_TYPE.UNPAID === orderInfo.status && <View className='float-box--height'/>}
      {/*{ORDER_TYPE.UNPAID === orderInfo.status && orderInfo.isProxyPay && <View className='fy-popup fy-popup--bottom float-box d-f a-i-c j-c-e'>*/}
      {/*  {PAY_TYPE.WECHAT === orderInfo.payType && <Button className='btn-box xf-btn xf-btn-danger xf-btn-round' onClick={this.onPayOrder.bind(this, orderInfo)}>立即代付</Button>}*/}
      {/*  {PAY_TYPE.WECHAT !== orderInfo.payType && <Button className='btn-box xf-btn xf-btn-danger xf-btn-round' onClick={this.showSelectPopup.bind(this, 'showWallet', true)}>立即代付</Button>}*/}
      {/*</View>}*/}
      {console.log(ORDER_TYPE.UNPAID)}
      {console.log(orderInfo.status)}
      {console.log(orderInfo.isProxyPay)}
      {console.log(orderInfo)}
      {ORDER_TYPE.UNPAID === orderInfo.status && <View className='fy-popup fy-popup--bottom float-box d-f a-i-c j-c-e'>
          <Button className='btn-box xf-btn xf-btn-round' onClick={this.onCloseOrder.bind(this, orderInfo.id)}>取消订单</Button>
        {/*{PAY_TYPE.WECHAT === orderInfo.payType && <Button openType='share' className='btn-box xf-btn xf-btn-round'>帮我付</Button>}*/}
        {/*{PAY_TYPE.WECHAT === orderInfo.payType && <Button className='btn-box xf-btn xf-btn-danger xf-btn-round' onClick={this.onPayOrder.bind(this, orderInfo)}>立即支付</Button>}*/}
        {/*{PAY_TYPE.WX_MP === orderInfo.payType && <Button className='btn-box xf-btn xf-btn-danger xf-btn-round' onClick={this.wechatPay.bind(this, orderInfo)}>立即支付</Button>}*/}
        <Button className='btn-box xf-btn xf-btn-danger xf-btn-round' onClick={this.getPay.bind(this, orderInfo)}>立即支付</Button>
        {/*{PAY_TYPE.WECHAT !== orderInfo.payType && <Button className='btn-box xf-btn xf-btn-danger xf-btn-round' onClick={this.showSelectPopup.bind(this, 'showWallet', true)}>立即支付</Button>}*/}
      </View>}
      {/*{ORDER_TYPE.UNPAID === orderInfo.status && <View className='fy-popup fy-popup--bottom float-box d-f a-i-c j-c-e'>*/}
      {/*  <Button className='btn-box xf-btn xf-btn-round' onClick={this.onCloseOrder.bind(this, orderInfo.id)}>取消订单</Button>*/}
      {/*  {PAY_TYPE.WECHAT === orderInfo.payType && <Button openType='share' className='btn-box xf-btn xf-btn-round'>帮我付</Button>}*/}
      {/*  {PAY_TYPE.WECHAT === orderInfo.payType && <Button className='btn-box xf-btn xf-btn-danger xf-btn-round' onClick={this.onPayOrder.bind(this, orderInfo)}>立即支付</Button>}*/}
      {/*  {PAY_TYPE.WECHAT !== orderInfo.payType && <Button className='btn-box xf-btn xf-btn-danger xf-btn-round' onClick={this.showSelectPopup.bind(this, 'showWallet', true)}>立即支付</Button>}*/}
      {/*</View>}*/}

      <WalletPay
        amount={orderInfo.payAmount}
        isOpened={showWallet}
        onClose={this.showSelectPopup.bind(this, 'showWallet', false)}
        onCancel={this.showSelectPopup.bind(this, 'showWallet', false)}
        onConfirm={this.onConfirmWalletPay.bind(this)}
      />
    </View>)
  }
}
